﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Properties;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;

namespace Finance.UI.Web
{
    public class JsonNetResult : JsonResult
    {
        public JsonNetResult(object data)
            : this(data, "application/json", Encoding.UTF8)
        {

        }
        public JsonNetResult(object data, string contentType)
            : this(data, contentType, Encoding.UTF8)
        {

        }

        public JsonNetResult(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior = JsonRequestBehavior.DenyGet)
        {
            this.Data = data;
            this.ContentType = contentType;
            this.ContentEncoding = contentEncoding;
            this.JsonRequestBehavior = behavior;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException();
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                var js = new JsonSerializer();
                var stringWriter = new StringWriter();
                js.Serialize(new CamelCaseStringWriter(stringWriter), Data);
                response.Write(stringWriter.ToString());
            }
        }


    }
}